package com.xywy.tangandroid.fragment;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.xywy.tangandroid.R;
import com.xywy.tangandroid.adapter.FamousDoctorAdapter;
import com.xywy.tangandroid.adapter.ProfessionAdapter;
import com.xywy.tangandroid.adapter.ProfessionAdapter.SetProfession;
import com.xywy.tangandroid.adapter.ProvinceAdapter;
import com.xywy.tangandroid.adapter.ProvinceAdapter.SetProvince;
import com.xywy.tangandroid.bean.Doctor;
import com.xywy.tangandroid.receiver.BroadcastAction;
import com.xywy.tangandroid.util.Constant;
import com.xywy.tangandroid.util.DeviceUtil;
import com.xywy.tangandroid.util.JsonUtil;
import com.xywy.tangandroid.util.LogUtil;
import com.xywy.tangandroid.util.NetUtil;
import com.xywy.tangandroid.util.UIUtil;
import com.xywy.tangandroid.vollery.GetRequest;
import com.xywy.tangandroid.vollery.OnVolleyResponseListener;
import com.xywy.tangandroid.vollery.VolleyManager;

/**
 * *****************************************
 * 
 * @Title: DoctorChurchFragement.java
 * @Package com.xywy.tangandroid.fragment
 * @Description: TODO(医生在线)
 * @author smz
 * @date 2014-12-4 下午1:17:37
 * @version V1.0
 ******************************************* 
 */
public class DoctorChurchFragement extends Fragment implements OnClickListener,
		OnScrollListener {

	protected static final int REQUESTERROR = 0;
	protected static final int SUCESS = 1;
	protected static final int PROVINCE = 2;
	protected static final int PROVINCEERROE = 3;
	public static final int REQUESTdOCTORLIST = -1;
	private ListView listview;
	private List<Doctor> list;
	// private List<ProvinceName> list1;
	private FamousDoctorAdapter adapter;
	protected ProgressDialog waittingDialog;

	private RelativeLayout choose_province_rel;
	private TextView choose_province_text;
	private RelativeLayout choose_work_rel;
	private ProvinceAdapter adapter1;
	// private List<User> list1;
	private PopupWindow window;

	private LinearLayout doctor_charch_rel;
	private TextView tv_msg;
	private LinearLayout loading;
	private LinearLayout list_footer;

	private int visibleLastIndex = 0; //

	private boolean isLoadMore = true;
	private int pageCount = 20;//
	private int pageNum = 1;//

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.fragement_doctorchurch, null);

		initView(view);
		initListener();
		initdata();
		return view;
	}

	private void initView(View view) {

		choose_province_rel = (RelativeLayout) view
				.findViewById(R.id.choose_province_rel);
		choose_work_rel = (RelativeLayout) view
				.findViewById(R.id.choose_work_rel);
		choose_province_text = (TextView) view
				.findViewById(R.id.choose_province_text);

		profession_text = (TextView) view.findViewById(R.id.profession_text);

		doctor_charch_rel = (LinearLayout) view
				.findViewById(R.id.doctor_charch_rel);

		listview = (ListView) view.findViewById(R.id.famous_doctor_listview);
		list = new ArrayList<Doctor>();
		// list1 = new ArrayList<ProvinceName>();

		//
		adapter1 = new ProvinceAdapter(getActivity(), Constant.province);

		adapter2 = new ProfessionAdapter(getActivity(), Constant.profession);
		initPopwindow();// popwindow 省份的
		initProvincePopWindow();// 职称的
		//
		list_footer = (LinearLayout) getActivity().getLayoutInflater().inflate(
				R.layout.list_footer, null);
		//
		list_footer.setVisibility(View.GONE);
		tv_msg = (TextView) list_footer.findViewById(R.id.tv_msg);
		loading = (LinearLayout) list_footer.findViewById(R.id.loading);
		listview.addFooterView(list_footer);

		IntentFilter filter = new IntentFilter(
				BroadcastAction.ACTION_SEND_EXPERT_LIST_REQUESTION);
		receiver = new BroadcasrReciver();
		getActivity().registerReceiver(receiver, filter);

	}

	public class BroadcasrReciver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			System.out.println("获取的广播是什么呢.." + intent.getAction());
			Message msg = Message.obtain();
			if ("action_send_expert_list_requestion".equals(intent.getAction())) {
				msg.what = REQUESTdOCTORLIST;
				handler.sendMessage(msg);
			}
		}

	}

	private void initListener() {
		listview.setOnScrollListener(this);
		choose_province_rel.setOnClickListener(this);
		choose_work_rel.setOnClickListener(this);

		adapter1.setView(new SetProvince() {

			@Override
			public TextView setprovince() {
				return choose_province_text;

			}

			@Override
			public PopupWindow popwindowNeedDismiss() {
				return window;
			}
		});

		// 选择职称的
		adapter2.setprofession(new SetProfession() {

			@Override
			public TextView setprofession() {
				return profession_text;
			}

			@Override
			public PopupWindow dismisspoppwindow() {
				return window2;
			}

		});

	}

	private void initdata() {

		// send();
		sendConditionDoctorList();
		adapter = new FamousDoctorAdapter(getActivity(), list, listview);
		listview.setAdapter(adapter);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.choose_province_rel://

			if (Constant.flag == true) {
				showPopWindow();
			}

			else {
				if (window.isShowing()) {
					window.dismiss();
					Constant.flag = true;
				}
			}
			// if (list1.size() == 0)//
			// getProvince();
			break;
		case R.id.choose_work_rel:

			if (Constant.flag_vocation == true) {
				showProfesstionWindow();
			}

			else {
				if (window2.isShowing()) {
					window2.dismiss();
					Constant.flag_vocation = true;
				}
			}

			break;

		default:
			break;
		}
	}

	private void getProvince() {
		final Message msg = Message.obtain();
		GetRequest<String> getRequest1 = new GetRequest<String>(
				Constant.getUrl("zhuanjia", "Province"), String.class,
				new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						LogUtil.i("..", volleyError + "");
						msg.what = REQUESTERROR;
						handler.sendMessage(msg);
					}

					@Override
					public void onSuccess(String response) {
						ParserProvinceJson(response);
						msg.what = PROVINCE;
						handler.sendMessage(msg);
					}
				});
		getRequest1.setIsParseJson(false);
		if (NetUtil.hasNetwork(getActivity())) {
			waitingDialog(getActivity(),
					getResources().getString(R.string.request));
			VolleyManager.addRequest(getRequest1, getActivity());
		} else {
			UIUtil.showToast(getActivity(),
					getResources().getString(R.string.not_network));
			UIUtil.DissDialog(getActivity(), waittingDialog);
		}
	}

	/**
    * 
    */
	private void send() {
		isLoadMore = true;
		final Message msg = Message.obtain();
		GetRequest<String> getRequest = new GetRequest<String>(Constant.getUrl(
				"zhuanjia", "AllDiabetesDoctor")
				+ "&provinceid=1&pageNum="
				+ pageNum + "&pageCount=" + pageCount, String.class,
				new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {

						LogUtil.i("..", volleyError + "");
						handler.sendMessage(msg);
						msg.what = REQUESTERROR;
					}

					@Override
					public void onSuccess(String response) {

						ParseDoctorJson(response);
						msg.what = SUCESS;
						handler.sendMessage(msg);

					}
				});
		getRequest.setIsParseJson(false);
		if (NetUtil.hasNetwork(getActivity())) {
			if (pageNum == 1)
				waitingDialog(getActivity(), getActivity().getResources()
						.getString(R.string.request));
			VolleyManager.addRequest(getRequest, getActivity());
		} else {
			UIUtil.showToast(getActivity(), getActivity().getResources()
					.getString(R.string.not_network));
			UIUtil.DissDialog(getActivity(), waittingDialog);
		}

	}

	public void waitingDialog(Context context, String message) {
		if (waittingDialog == null)
			waittingDialog = new ProgressDialog(context);
		waittingDialog.setCanceledOnTouchOutside(false);//
		waittingDialog.setMessage(message);
		waittingDialog.show();
	}

	private void ParserProvinceJson(String value) {
		try {
			JSONObject object = new JSONObject(value);

			String data = object.optString("data");
			//
			// list1.addAll((List<ProvinceName>) JsonUtil.parseJsonToList(data,
			// new TypeToken<List<ProvinceName>>() {
			// }.getType()));
		} catch (Exception e) {
			LogUtil.i("DoctorChurchFragement", "Json解析异常");
			e.printStackTrace();
		}
	}

	private void ParseDoctorJson(String value) {
		try {
			JSONObject object = new JSONObject(value);
			String data = object.optString("data");

			list.addAll((List<Doctor>) JsonUtil.parseJsonToList(data,
					new TypeToken<List<Doctor>>() {
					}.getType()));
		} catch (Exception e) {
			LogUtil.i("DoctorChurchFragement", "Json解析异常");
			e.printStackTrace();
		}
	}

	/**
	 * popwindow
	 */
	private void initPopwindow() {

		View popupView = getActivity().getLayoutInflater().inflate(
				R.layout.popwindow_item, null);
		ListView lv = (ListView) popupView.findViewById(R.id.pop_listview);

		lv.setAdapter(adapter1);//
		width = DeviceUtil.getDeviceWidth(getActivity()) / 2;
		int height = WindowManager.LayoutParams.WRAP_CONTENT;
		window = new PopupWindow(popupView, width, height);
		window.setTouchable(true);
	}

	private void initProvincePopWindow() {
		View popupView2 = getActivity().getLayoutInflater().inflate(
				R.layout.popwindow_item, null);
		ListView lv2 = (ListView) popupView2.findViewById(R.id.pop_listview);

		lv2.setAdapter(adapter2);//

		width = DeviceUtil.getDeviceWidth(getActivity()) / 2;
		int height = WindowManager.LayoutParams.WRAP_CONTENT;
		window2 = new PopupWindow(popupView2, width, height);
		window2.setTouchable(true);
	}

	private void showProfesstionWindow() {
		window2.showAsDropDown(choose_work_rel, width, 0);
		Constant.flag_vocation = false;
	}

	private void showPopWindow() {

		window.showAsDropDown(doctor_charch_rel);//
		Constant.flag = false;

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		visibleLastIndex = firstVisibleItem + visibleItemCount;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		int itemsLastIndex = adapter.getCount(); //
		int lastIndex = itemsLastIndex + 1; //
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
				&& visibleLastIndex == lastIndex) {
			if (isLoadMore) {
				isLoadMore = false;
				pageNum++;
				Log.i("pageNo", "...." + pageNum + ".....");
				tv_msg.setVisibility(View.GONE);
				loading.setVisibility(View.VISIBLE);
				// send();
				sendConditionDoctorList();
			}
		}
	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case REQUESTERROR:
				UIUtil.DissDialog(getActivity(), waittingDialog);
				UIUtil.showToast(getActivity(), getActivity().getResources()
						.getString(R.string.network_slow));
				break;

			case SUCESS:
				if (list.size() > 0 & list.size() <= pageCount * pageNum
						&& pageCount > 0) {
					list_footer.setVisibility(View.VISIBLE);
					tv_msg.setVisibility(View.VISIBLE);
					loading.setVisibility(View.GONE);
				}

				if (list.size() < 20 || list.size() < pageCount * pageNum) {
					// list_footer.setVisibility(View.GONE);
					listview.removeFooterView(list_footer);

				}
				UIUtil.DissDialog(getActivity(), waittingDialog);
				adapter.notifyDataSetChanged();

				break;
			case PROVINCE:
				UIUtil.DissDialog(getActivity(), waittingDialog);
				adapter1.notifyDataSetChanged();
				break;
			case REQUESTdOCTORLIST:// 根据地区 和职称 选择医生的列表
				pageNum = 1;// 重新请求
				list.clear();// 将里面的内容全部清除
				sendConditionDoctorList();
				break;
			default:
				break;
			}
		}
	};

	private int width;
	private ProfessionAdapter adapter2;
	private PopupWindow window2;
	private TextView profession_text;
	// private BroadcastReceiver myReceiver;
	private BroadcasrReciver receiver;

	@Override
	public void onStop() {
		super.onStop();
		if (window != null && window.isShowing()) {
			window.dismiss();
			Constant.flag = true;
		}

		if (window2 != null && window2.isShowing()) {
			window2.dismiss();
			Constant.flag_vocation = true;
		}
	}

	protected void sendConditionDoctorList() {
		String addurl = "";
		String province;

		isLoadMore = true;
		final Message msg = Message.obtain();
		try {
			province = URLEncoder.encode(Constant.PPROVINCE, "utf-8");
			String profession = URLEncoder.encode(Constant.PROFESSION, "utf-8");
			System.out.println("获取的职称...." + Constant.PROFESSION);
			System.out.println("获取的地区..." + Constant.PPROVINCE);

			if (Constant.PROFESSION.length() > 0
					&& Constant.PPROVINCE.length() > 0) {
				addurl = "&title=" + profession + "&province=" + province
						+ "&pageNum=" + pageNum + "&pageCount=" + pageCount;
			} else if (Constant.PROFESSION.length() > 0
					&& Constant.PPROVINCE.length() == 0) {
				addurl = "&title=" + profession + "&pageNum=" + pageNum
						+ "&pageCount=" + pageCount;
			} else if (Constant.PROFESSION.length() == 0
					&& Constant.PPROVINCE.length() > 0) {
				addurl = "&province=" + province + "&pageNum=" + pageNum
						+ "&pageCount=" + pageCount;
			} else if (Constant.PROFESSION.length() == 0
					&& Constant.PPROVINCE.length() == 0) {
				addurl = "&pageNum=" + pageNum + "&pageCount=" + pageCount;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("..............连接"
				+ Constant.getUrl("zhuanjia", "TitleDoctor") + addurl);
		GetRequest<String> request = new GetRequest<String>(Constant.getUrl(
				"zhuanjia", "TitleDoctor") + addurl, String.class,
				new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						// LogUtil.i("按条件请求", volleyError + "");
						// UIUtil.DissDialog(getActivity(), waittingDialog);

						LogUtil.i("..", volleyError + "");

						handler.sendMessage(msg);
						msg.what = REQUESTERROR;
					}

					@Override
					public void onSuccess(String response) {
						// UIUtil.DissDialog(getActivity(), waittingDialog);
						// System.out.println("获取的返回的数据" + response);

						ParseDoctorJson(response);
						msg.what = SUCESS;
						handler.sendMessage(msg);
					}
				});
		request.setIsParseJson(false);
		if (NetUtil.hasNetwork(getActivity())) {
			if (pageNum == 1)
				waitingDialog(getActivity(), getActivity().getResources()
						.getString(R.string.request));
			VolleyManager.addRequest(request, getActivity());
		} else {
			UIUtil.showToast(getActivity(), getActivity().getResources()
					.getString(R.string.not_network));
			UIUtil.DissDialog(getActivity(), waittingDialog);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		VolleyManager.cancelRequest(getActivity());
	}
}
